package servlet.song;

import service.SongsService;
import service.impl.SongsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

@WebServlet("/song/delete")
public class Delete extends HttpServlet {

    private static final Logger logger = Logger.getLogger(Delete.class.getName());
    private SongsService songsService = new SongsServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 获取要删除的歌曲 ID，并进行参数校验
            String songIdParam = req.getParameter("songsId");
            if (songIdParam == null || songIdParam.isEmpty()) {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().write("<script>alert('歌曲ID不能为空');window.history.back();</script>");
                return;
            }

            int songId;
            try {
                // 将参数转换为 int 类型
                songId = Integer.parseInt(songIdParam);
            } catch (NumberFormatException e) {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().write("<script>alert('歌曲ID无效');window.history.back();</script>");
                return;
            }

            // 调用服务层删除歌曲
            boolean isDeleted = songsService.deleteById(songId);

            if (isDeleted) {
                // 删除成功，重定向到歌曲列表页面
                resp.sendRedirect("/song/list.jsp");
            } else {
                // 删除失败，返回错误提示
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                resp.getWriter().write("<script>alert('歌曲删除失败');window.history.back();</script>");
            }
        } catch (Exception e) {
            // 记录异常日志
            logger.log(Level.SEVERE, "删除歌曲时发生异常", e);

            // 返回服务器错误响应
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().write("<script>alert('服务器发生错误，请稍后再试');window.history.back();</script>");
        }
    }
}
